

((_global_)=>{
	if(!Reflect.has(_global_, 'mtec')){
		Reflect.set(_global_, 'mtec', {});
		Reflect.set(mtec, '__mtec__', 'Many technologies');
	}

	if(!mtec.local){
		Reflect.set(mtec, 'local', {});
	}
	Reflect.set(mtec.local, '__space_description__', 'This is a mtec subnamespace for local');
})(window ?? globalThis);

const local_map: Map<string, any> = new Map();

function read_from_local(key: string){
	key = key.encodeBtoA;
	if(local_map.has(key)){
		return local_map.get(key);
	}else{
		let data_json = localStorage.getItem(key);

		if(data_json){
			let data: any;
			try{
				data = mtec.parseJson(data_json.decodeAtoB);
			}catch(e){
				console.warn('[read_from_local] Error parsing JSON data from localStorage:', e);
				console.log('Error [data_json]:', data_json, data_json.decodeAtoB);
			}

			local_map.set(key, data);
			return data;
		}
		return void 0;
	}
}

var local_saving = false;
var save_key_list: string[] = [];
var save_index = 0;
var save_key: string;
var save_json: string;
async function run_save_task(key: string){
	if(save_key_list.indexOf(key) <= save_index){
		save_key_list.push(key);
	}

	if(local_saving){
		return void 0;
	}
	local_saving = true;

	while(save_index < save_key_list.length){
		save_key = save_key_list[save_index];
		try{
			save_json = mtec.JsonString(local_map.get(save_key));
			if(save_json){
				localStorage.setItem(save_key, save_json.encodeBtoA);
			}
		}catch(e){
			console.warn('[run_save_task] Error saving data to localStorage:', e);
		}

		save_index = save_index + 1;
	}

	save_key = save_json = undefined;

	save_key_list.length = 0;
	save_index = 0;
	local_saving = false;
}

var local_removing = false;
var remove_key_list: string[] = [];
var remove_index = 0;
async function run_remove_task(key: string){
	if(remove_key_list.indexOf(key) <= remove_index){
		remove_key_list.push(key);
	}

	if(local_removing){
		return void 0;
	}
	local_removing = true;

	while(remove_index < remove_key_list.length){
		localStorage.removeItem(remove_key_list[remove_index]);
		remove_index = remove_index + 1;
	}

	remove_key_list.length = 0;
	remove_index = 0;
	local_removing = false;
}

mtec.local.read = function(key, out){
	let data = read_from_local(key);

	if(data){
		if(typeof data=='object'){
			if(out){
				Object.assign(out, data);
			}else{
				out = data;
			}
		}else{
			out = data;
		}
		data = undefined;
	}

	return out as any;
}

mtec.local.save = function(key, data){
	key = key.encodeBtoA;
	local_map.set(key, mtec.cloneData(data));
	run_save_task(key);
}

mtec.local.remove = function(key){
	key = key.encodeBtoA;
	local_map.set(key, undefined);
	run_remove_task(key);
}

mtec.local.has = function(key){
	key = key.encodeBtoA;
	if(local_map.has(key)){
		return local_map.get(key) !== undefined;
	}else{
		for(let i = 0; i < localStorage.length; i++){
			if(localStorage.key(i) == key){
				return true;
			}
		}
		return false;
	}
}